<?php
namespace app\home\controller;
/*                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
*             __.'              ~.   .~              `.__
*           .'//        保佑      \./        无bug      \\`.
*         .'//                     |                     \\`.
*       .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-. \\`.
*     .'//.-"                 `-.  |  .-'                 "-.\\`.
*   .'//______.============-..   \ | /   ..-============.______\\`.
 .'______________________________\|/______________________________`.
     后台登陆控制器
 */
use think\Controller;
use app\common\model\system\SystemAdmin;
use app\common\controller\HomeController;
use think\facade\Env;
use think\captcha\facade\Captcha;
/**
 * Class Login
 * @package app\admin\controller
 */
class Login extends HomeController
{
    /**
     * 退出登陆
     * @return \think\response\Json
     */
    public function logout()
    {
        $data = [
            'code' => 200 ,
            'msg' => '退出成功...' ,

        ];
        return json($data);
    }
    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function login()
    {

        if ($this->request->isPost()) {
            $post = $this->request->param();
            try{
                $rule = [
                    'username|用户名'      => 'require',
                    'password|密码'       => 'require',
                   // 'captcha|验证码'=>'require|captcha'
                ];
                $this->validate($post, $rule);
                $admin = SystemAdmin::where(['username' => $post['username']])->find();
                if (empty($admin)) {
                    throw new \Exception('用户不存在');
                }
                if (password($post['password']) != $admin->password) {
                    throw new \Exception('密码输入有误');
                }
                if ($admin->status == 0) {
                    throw new \Exception('账号已被禁用');
                }
                $admin = $admin->toArray();

                unset($admin['password']);
                $admin['expire_time'] =  time() + 7200;
                session('admin', $admin);

                $data = [
                    'code' => 200,
                    'msg' => '登录成功...',
                    'data' => [
                        'accessToken' => "".$admin['id']."",
                        //'user_id'     =>$admin['id'],
                    ]
                ];


            }catch(\Exception $e){
                $data = [
                    'code' => 202,
                    'msg' => $e->getMessage(),
                ];

            }
            return json($data);


        }

        return view();
    }




}